<template>
    <j-modal
      :width="modalWidth"
      :visible="visible"
      :title="title"
      switchFullscreen
      @ok="handleSubmit"
      @cancel="close"
      style="top: 50px"
      cancelText="关闭"
    >
      <a-card :bordered="false">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <a-form layout="inline" @keyup.enter.native="searchQuery">
            <a-row :gutter="24">
              <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="物料编码">
                <a-input placeholder="请输入物料编码" v-model="queryParam.materialCode"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="物料名称">
                <a-input placeholder="请输入物料名称" v-model="queryParam.materialName"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="批次号">
                <a-input placeholder="请输入批次号" v-model="queryParam.batchNumber"></a-input>
              </a-form-item>
            </a-col>
              <a-col :xl="6" :lg="7" :md="8" :sm="24">
                <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
                  <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                  <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <!-- <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
          <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
          <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
          >项
          <a style="margin-left: 24px" @click="onClearSelected">清空</a>
        </div> -->
        <div>
          <a-table
            ref="table"
            size="middle"
            :scroll="{ x: true }"
            bordered
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: checkval }"
            class="j-table-force-nowrap1"
            @change="handleTableChange"
          >
            <template slot="htmlSlot" slot-scope="text">
              <div v-html="text"></div>
            </template>
            <template slot="imgSlot" slot-scope="text, record">
              <span v-if="!text" style="font-size: 12px; font-style: italic">无图片</span>
              <img
                v-else
                :src="getImgView(text)"
                :preview="record.id"
                height="25px"
                alt=""
                style="max-width: 80px; font-size: 12px; font-style: italic"
              />
            </template>
            <template slot="fileSlot" slot-scope="text">
              <span v-if="!text" style="font-size: 12px; font-style: italic">无文件</span>
              <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
                下载
              </a-button>
            </template>
          </a-table>
        </div>
      </a-card>
    </j-modal>
  </template>
  
  <script>
  import '@/assets/less/TableExpand.less'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { deleteAction, getAction, httpAction } from '@api/manage'
  
  export default {
    name: 'MaterialListModal',
    mixins:[JeecgListMixin],
    components: {},
    props: {
      modalWidth: {
        type: Number,
        required: false,
        default: 1250,
      },
      checkval: {
        type: String,
        default: 'radio',
      },
    },
    data() {
      return {
        visible:false,
        title: '选择物料',
        description: '物料信息表',
        activeKey: 'on',
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '100', '3000'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0,
        },
        // 表头
        columns: [
            {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 40,
            align: 'center',
            fixed: 'left',
            customRender: function(t, r, index) {
                return parseInt(index) + 1
            }
            },
            {
            title: '物料编码',
            align: 'center',
            dataIndex: 'materialCode',
            fixed: 'left'
            },
            {
            title: '物料名称',
            align: 'center',
            dataIndex: 'materialName',
            fixed: 'left'
            },
            {
            title: '客户物料编码',
            align: 'center',
            dataIndex: 'customerMaterialCode'
            },
            {
            title: '批次号',
            align: 'center',
            dataIndex: 'batchNumber'
            },
            {
            title: '物料批号',
            align: 'center',
            dataIndex: 'materialBatchNumber'
            },
            {
            title: '储位',
            align: 'center',
            dataIndex: 'storageLocation_dictText'
            },
            {
            title: '规格型号',
            align: 'center',
            dataIndex: 'specificationModel'
            },
            {
            title: '物料描述',
            align: 'center',
            dataIndex: 'materialDesc'
            },
            {
            title: '单位',
            align: 'center',
            dataIndex: 'unit_dictText'
            },
            {
            title: '数量',
            align: 'center',
            dataIndex: 'quantity'
            },
            {
            title: '辅单位',
            align: 'center',
            dataIndex: 'secondaryUnit_dictText'
            },
            {
            title: '辅数量',
            align: 'center',
            dataIndex: 'secondaryQuantity'
            },
            {
            title: '生产日期',
            align: 'center',
            dataIndex: 'productionDate',
            customRender: function(text) {
                return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
            }
            },
            {
            title: '保质期（天）',
            align: 'center',
            dataIndex: 'shelfLife'
            },
            {
            title: '限用日期',
            align: 'center',
            dataIndex: 'expirationDate',
            customRender: function(text) {
                return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
            }
            },
            {
            title: '入库日期',
            align: 'center',
            dataIndex: 'entryDate',
            customRender: function(text) {
                return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
            }
            },
            {
            title: '库龄（天）',
            align: 'center',
            dataIndex: 'inventoryAge'
            },
            {
            title: '质检状态',
            align: 'center',
            dataIndex: 'qualityInspectionStatus_dictText'
            },
            {
            title: '物料类型',
            align: 'center',
            dataIndex: 'materialClassify_dictText'
            },
            {
            title: '检验标准',
            align: 'center',
            dataIndex: 'inspectionStandard'
            },
            {
            title: '抽检数量',
            align: 'center',
            dataIndex: 'samplingQuantity'
            },
            {
            title: '检验结果',
            align: 'center',
            dataIndex: 'inspectionResult'
            },
            {
            title: '检验人',
            align: 'center',
            dataIndex: 'inspector'
            },
            {
            title: '检验部门',
            align: 'center',
            dataIndex: 'inspectionDeptCode_dictText'
            },
            {
            title: '检验日期',
            align: 'center',
            dataIndex: 'inspectionDate',
            customRender: function(text) {
                return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
            }
            },
            {
            title: '备注',
            align: 'center',
            dataIndex: 'remark',
            scopedSlots: { customRender: 'remark' }
            },
        ],
        url: {
            list: '/feedingbefore/erpProductionFeedingBefore/queryWarehouseMaterials',
            checkMaterial: '/feedingbefore/erpProductionFeedingBefore/checkMaterial',
        },
        queryParam: {},
        superFieldList: [],
        // 固定查询条件
        fixedQueryParams: {},
        // 校验传值
        checkParams: {},
      }
    },
    created() {
      this.loadData()
    },
    computed: {
    },
    methods: {
      close() {
        this.queryParam = {materialCode:'',materialName:''}
        this.selectedRowKeys = []
        this.selectionRows = []
        this.visible = false;
      },
      add(params) {
        this.checkParams = params
        // 保存固定查询参数
        this.fixedQueryParams = {
            sysOrgCode: params.workshopCode
        }
        // 应用固定查询条件
        this.queryParam = {
            ...this.queryParam,
            ...this.fixedQueryParams
        }
        this.visible = true;
        this.loadData();
      },
      searchReset() {
      // 重置时保留固定参数
        this.queryParam = {
            materialCode: '',
            materialName: '',
            ...this.fixedQueryParams // 保留固定条件
        }
        this.loadData();
      },
      handleSubmit() {
        let selectedRows = [];
        if (this.checkval === 'radio' && this.selectionRows.length > 0) {
            selectedRows = [this.selectionRows[0]];
        } else {
            selectedRows = [...this.selectionRows];
        }
        // 检查是否选中了物料
        if (selectedRows.length === 0) {
            this.$message.warning("请选择物料");
            return;
        }
        let queryParam = {
            ...this.checkParams,
            materialCode: selectedRows[0].materialCode
        }
        if(this.checkParams.ifPackage){
          queryParam.packageCode = selectedRows[0].materialCode
        }
        // 调用检查接口
        getAction(this.url.checkMaterial, queryParam).then((res) => {
            if (res.success) {
                if(!res.result) {
                    let content = this.checkParams.ifPackage?'该物料不在包材清单内，是否继续？':'该物料不在配方内，是否继续？'
                    // 物料不在配方内，弹出确认框
                    this.$confirm({
                        title: '提示',
                        content: content,
                        okText: '继续',
                        cancelText: '取消',
                        onOk: () => {
                            // 用户确认继续，提交数据
                            this.$emit("ok", selectedRows);
                            this.close();
                        },
                        onCancel: () => {
                            // 用户取消，不做任何操作（只关闭确认框）
                        }
                    });
                } else {
                    // 物料在配方内，直接提交数据
                    this.$emit("ok", selectedRows);
                    this.close();
                }
            } else {
                this.$message.warning(res.message)
            }
        })
        // 添加错误处理
        .catch(error => {
            this.$message.error("检查物料失败：" + error.message);
        });
      },
      getSelectRows() {
        let selectedRow = null;
        if(this.checkval=='radio'){
           selectedRow = this.selectionRows[0];
        }else{
           selectedRow = this.selectionRows
        }
        //传递选中的数据
        this.$emit("handlerOk", selectedRow);
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectionRows = selectionRows
      },
      modalFormOk() {
        this.loadData()
      },
      loadData() {
        // 添加判断：只有在弹窗可见时才执行查询
        if (!this.visible) return;
        this.loading = true
        getAction(this.url.list, this.queryParam)
          .then((res) => {
            if (res.success) {
              //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
              this.dataSource = res.result.records || res.result
              if (res.result.total) {
                this.ipagination.total = res.result.total
              } else {
                this.ipagination.total = 0
              }
              //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            } else {
              this.$message.warning(res.message)
            }
          })
          .finally(() => {
            this.loading = false
          })
      },
      initDictConfig() {},
    },
  }
  </script>
  <style scoped>
  @import '~@assets/less/common.less';
  </style>
  